//
//  VRSchedulingViewController.m
//  testForAreacode
//
//  Created by Veer on 16/6/3.
//  Copyright © 2016年 Veer. All rights reserved.
//

#import "YAYISchedulingViewController.h"
#import "YAYIDateController.h"
#import "YAYILoginViewController.h"

#import "YAYISchedulingView.h"
#import "YAYISchedulingCell.h"
#import "YAYILineView.h"
#import "YAYICalendarCell.h"
#import "YAYIHospitalDropListView.h"
#import "YAYIShareView.h"

#import "YAYICalendarModel.h"
#import "YAYISchededdModel.h"
#import "YAYISchedulingItemModel.h"



#define CalenDarTag 100
#define HaveBookingAlertTag 200
#define CopyLastWeekAlertTag 300
#define ClearThisWeekAlertTag 400
#define ClearThisWeekHaveBookingAlertTag 500
#define NotLoginAlertTag 600


@interface YAYISchedulingViewController () <UITableViewDelegate, UITableViewDataSource, YAYISchedulingCellDelegate, YAYIHospitalDropListViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource, UIAlertViewDelegate>

@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, weak) UITableView *calendarTableView;
@property (nonatomic, weak) UIButton *monthBtn;

// 选择器相关
@property (nonatomic, weak) UIButton *treatCountBtn;
@property (nonatomic, weak) UIView *maskView;
@property (nonatomic, weak) UIView *dateSelectView;
@property (nonatomic, weak) UIDatePicker *datePicker;
@property (nonatomic, weak) UIPickerView *pickerView;


@property (nonatomic, strong) NSMutableArray *itemViewArray;
@property (nonatomic, strong) NSMutableArray *schedulingModelArray;

@property (nonatomic, assign) CGFloat cellHeight;
@property (nonatomic, assign) CGFloat timeWidth;
/**
 *  保存更改过的itemView
 */
@property (nonatomic, strong) NSMutableDictionary *changedItemDict;

/**
 *  日历相关
 */
@property (nonatomic, strong) NSMutableArray *dateModelArray;
@property (nonatomic, assign) NSInteger dayCount;
@property (nonatomic, assign) NSInteger startDayTimeStamp;
@property (nonatomic, assign) NSInteger todayWeekDay;
/**
 *  存储日历表跨月份数组，存储如201606
 */
@property (nonatomic, strong) NSMutableArray *monthParamArray;
/**
 *  滚动到第几周
 */
@property (nonatomic, assign) NSInteger weekIndex;

/**
 *  dropList
 */
@property (nonatomic, weak) YAYIHospitalDropListView *dropMenu;
@property (nonatomic, strong) NSMutableArray *hospitalArray;
@property (nonatomic, copy) NSString *hospitalID;


@property (nonatomic, weak) UIView *leftLineView;

/**
 *  用于给alertView传参
 */
@property (nonatomic, strong) NSMutableDictionary *param;
@property (nonatomic, copy) NSString *bookingTimeids;

@property (nonatomic, assign) BOOL isHaveInit;

@end

@implementation YAYISchedulingViewController

- (NSMutableArray *)schedulingModelArray
{
    if (nil == _schedulingModelArray) {
        _schedulingModelArray = [NSMutableArray array];
        
        for (int i = 0; i < self.dateModelArray.count; i++) {
            YAYICalendarModel *calendarModel = self.dateModelArray[i];
            
            YAYISchedulingItemModel *model = [[YAYISchedulingItemModel alloc] init];
            model.dateStamp = calendarModel.dateStamp;
            model.isExpired = NO;
            if (i < self.todayWeekDay + 7) {
                model.isExpired = YES;
            }
            [_schedulingModelArray addObject:model];
        }
        
    }
    return _schedulingModelArray;
}

- (NSMutableArray *)dateModelArray
{
    if (nil == _dateModelArray) {
        _dateModelArray = [NSMutableArray array];
        
        NSInteger todayWeekDay = [self weekdayInToday:[NSDate date]];
        self.todayWeekDay = todayWeekDay;
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"YYYY-MM-dd";
        NSString *dateStr = [formatter stringFromDate:[NSDate date]];
        NSDate *todayDate = [formatter dateFromString:dateStr];
        
        NSInteger todayDayStamp = [todayDate timeIntervalSince1970];
        NSInteger startDayStamp = todayDayStamp - (todayWeekDay + 7) * 24 * 60 * 60;
        self.startDayTimeStamp = startDayStamp;
        
        NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:startDayStamp];
        YAYILog(@"startDate:%@", startDate);
        
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        calendar.locale = [NSLocale systemLocale];
        NSDateComponents *comps = [[NSDateComponents alloc] init];
        NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
        
//        if ((30 + todayWeekDay) % 7 > 0) {
//            self.dayCount = (NSInteger)((30 + todayWeekDay) / 7) * 7 + 7;
//        }else{
//            self.dayCount = 30 + todayWeekDay;
//        }
        self.dayCount = 35;
        self.monthParamArray = [NSMutableArray array];
        NSInteger monthTemp = 0;
        for (int i = 0; i < self.dayCount; i++) {
            NSInteger dateStamp = startDayStamp + i * 24 * 60 * 60;
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:dateStamp];
            comps = [calendar components:unitFlags fromDate:date];
            
            if (monthTemp != comps.month) {
                NSString *monthStr = [NSString stringWithFormat:@"%ld%02ld", comps.year, comps.month];
                [self.monthParamArray addObject:monthStr];
            }
            monthTemp = comps.month;
            
            YAYICalendarModel *model = [[YAYICalendarModel alloc] init];
            model.year = comps.year;
            model.month = comps.month;
            model.day = comps.day;
            model.week = comps.weekday;
            model.date = date;
            model.dateStamp = dateStamp;
            
            if (i == todayWeekDay + 7) {
                model.isToday = YES;
            }
            
            [self.dateModelArray addObject:model];
        }
    }
    return _dateModelArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.changedItemDict = [NSMutableDictionary dictionary];
    
    [self setupNav];
    [self setupTableView];
    [self setupTimeLbl];
    [self setupCalendar];
    [self setupBottomView];
    // 注意：下拉列表必须放在最后初始化
    [self setupDropMenu];
    [self getHospitalList];
    
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (!self.isHaveInit) {
        [self.tableView setContentOffset:CGPointMake(0, 7 * self.cellHeight) animated:YES];
        self.isHaveInit = YES;
    }
    
}


- (void)setupNav
{
    NSString *rightBtnTitleStr = @"分享";
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [button setImage:[UIImage imageNamed:@"back_button"] forState:UIControlStateNormal];
    [button setTitle:rightBtnTitleStr forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    
    button.frame = (CGRect){{0, 0}, CGSizeMake(50, 30)};
    
    // 让按钮内部的所有内容左对齐
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [button addTarget:self action:@selector(onSaveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    // 修改导航栏左边的item
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}


- (void)setupDropMenu
{
    //上边按钮展示的模型,此模型对text赋值即可.
    self.hospitalArray = [NSMutableArray array];
    
    //若列表展示内容与按钮展示内容相同则showArr传nil即可。
    YAYIHospitalDropListView *dropMenu = [[YAYIHospitalDropListView alloc] initWithFrame:CGRectMake(70, 0, SCREEN_width - 70 * 2, 36) showOnView:self.view AllDataArr:self.hospitalArray showArr:@"选择医院"];
    dropMenu.delegate = self;
    self.dropMenu = dropMenu;
    self.navigationItem.titleView = dropMenu;
}


- (void)setupGrid
{
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    [self.view addSubview:scrollView];
    scrollView.frame = CGRectMake(44, 100, SCREEN_width - 44, 400);

    CGFloat itemW = (SCREEN_width - 40) / 7.0;
    CGFloat itemH = 400 / 12.0;
    
    for (int i = 0; i < 30; i++) {
        for (int j = 0; j < 11; j++) {
            
            UIView *vLineView = [[UIView alloc] init];
            vLineView.backgroundColor = YAYIColor(0xdd, 0xdd, 0xdd);
            [scrollView addSubview:vLineView];
            [vLineView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(0.5);
                make.height.mas_equalTo(itemH);
                make.right.mas_equalTo(scrollView.mas_left).offset((i + 1) * itemW);
                make.top.mas_equalTo(j * itemH);
            }];
            
            UIView *hLineView = [[UIView alloc] init];
            hLineView.backgroundColor = YAYIColor(0xdd, 0xdd, 0xdd);
            [scrollView addSubview:hLineView];
            [hLineView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(0.5);
                make.width.mas_equalTo(itemW);
                make.left.mas_equalTo(i * itemW);
                make.bottom.mas_equalTo(scrollView.mas_top).offset((j + 1) * itemH);
            }];
        }
    }
    
    scrollView.contentSize = CGSizeMake(itemW * 30, 0);
}


- (void)setupTableView
{
    // 计算cell高度
    CGFloat cellHeight = (SCREEN_width - 44 * YAYIScreenScale) / 7.0;
    NSInteger i = (NSInteger)cellHeight;
    // 保证浮点数是0.5的倍数
    CGFloat f = cellHeight - i;
    if (f >= 0.25) {
        self.cellHeight = i + 0.5;
    }else{
        self.cellHeight = i;
    }

    // 计算左边
    self.timeWidth = SCREEN_width - 7 * self.cellHeight;
    CGFloat tableH = SCREEN_height - 64 - 200 * YAYIScreenScale;
    // 保证浮点数是0.5的倍数
    NSInteger i2 = (NSInteger)tableH;
    CGFloat f2 = tableH - i;
    if (f2 >= 0.25) {
        tableH = i2 + 0.5;
    }else{
        tableH = i2;
    }
    
    UIView *blankView = [[UIView alloc] init];
    [self.view addSubview:blankView];
    
    UITableView *tableView = [[UITableView alloc] init];
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.transform = CGAffineTransformMakeRotation(-M_PI_2);
    tableView.frame = CGRectMake(self.timeWidth, 100 * YAYIScreenScale + 64, 7 * self.cellHeight, tableH);
//    tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    tableView.showsVerticalScrollIndicator = NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.pagingEnabled = YES;
    [self.view addSubview:tableView];
    self.tableView = tableView;
}



- (void)setupTimeLbl
{
    CGFloat itemH = self.tableView.frame.size.height / 12.0;
    NSArray *titleArray = @[@"上\n\n\n午", @"下\n\n\n午"];
    for (int i = 0; i < 2; i++) {
        UILabel *timeLbl = [[UILabel alloc] init];
        timeLbl.numberOfLines = 0;
        timeLbl.font = [UIFont systemFontOfSize:14];
        timeLbl.textColor = YAYIColor(130, 130, 130);
        timeLbl.textAlignment = NSTextAlignmentCenter;
        timeLbl.text = titleArray[i];
        [self.view addSubview:timeLbl];
        [timeLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.view);
            make.right.mas_equalTo(self.tableView.mas_left);
            make.top.mas_equalTo(self.tableView.mas_top).offset(i * itemH * 4 + (i + 1) * itemH);
            make.height.mas_equalTo(itemH * 4 );
        }];
    }
    
    
    // 最左边线
    UIView *lineView = [[UIView alloc] init];
    [self.view addSubview:lineView];
    self.leftLineView = lineView;
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.tableView.mas_left);
        make.top.mas_equalTo(self.tableView.mas_top).offset(0 * itemH);
        make.width.mas_offset(1.0);
        make.height.mas_equalTo(itemH);
    }];
    
    UIView *vLineView1 = [[UIView alloc] init];
    vLineView1.backgroundColor = YAYIColor(180, 180, 180);
    [lineView addSubview:vLineView1];
    [vLineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(lineView);
        make.top.mas_equalTo(self.tableView.mas_top).offset(0 * itemH);
        make.width.mas_offset(0.5);
        make.height.mas_equalTo(itemH);
    }];
    
    YAYILineView *vLineView2 = [[YAYILineView alloc] init];
    vLineView2.lineColor = YAYIColor(104, 174, 240);
    vLineView2.lineDirect = LineDirectV;
    [lineView addSubview:vLineView2];
    [vLineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(lineView);
        make.top.mas_equalTo(self.tableView.mas_top).offset(1 * itemH);
        make.width.mas_offset(1.0);
        make.height.mas_equalTo(4 * itemH);
    }];
    
    UIView *vLineView3 = [[UIView alloc] init];
    vLineView3.backgroundColor = YAYIColor(180, 180, 180);
    [lineView addSubview:vLineView3];
    [vLineView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(lineView);
        make.top.mas_equalTo(self.tableView.mas_top).offset(5 * itemH);
        make.width.mas_offset(0.5);
        make.height.mas_equalTo(itemH);
    }];
    
    YAYILineView *vLineView4 = [[YAYILineView alloc] init];
    vLineView4.lineColor = YAYIColor(104, 174, 240);
    vLineView4.lineDirect = LineDirectV;
    [lineView addSubview:vLineView4];
    [vLineView4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(lineView);
        make.top.mas_equalTo(self.tableView.mas_top).offset(6 * itemH);
        make.width.mas_offset(1.0);
        make.height.mas_equalTo(4 * itemH);
    }];
    
    UIView *vLineView5 = [[UIView alloc] init];
    vLineView5.backgroundColor = YAYIColor(180, 180, 180);
    [lineView addSubview:vLineView5];
    [vLineView5 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(lineView);
        make.top.mas_equalTo(self.tableView.mas_top).offset(10 * itemH);
        make.width.mas_offset(0.5);
        make.height.mas_equalTo(2 * itemH);
    }];
//
    
}

- (void)setupCalendar
{
    UITableView *calendarTableView = [[UITableView alloc] init];
    calendarTableView.tag = CalenDarTag;
    calendarTableView.backgroundColor = [UIColor whiteColor];
    calendarTableView.transform = CGAffineTransformMakeRotation(-M_PI_2);
    calendarTableView.frame = CGRectMake(self.timeWidth, 64, 7 * self.cellHeight, 64);
//    calendarTableView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0);
    calendarTableView.showsVerticalScrollIndicator = NO;
    calendarTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    calendarTableView.scrollEnabled = NO;
    calendarTableView.delegate = self;
    calendarTableView.dataSource = self;
//    calendarTableView.pagingEnabled = YES;
    [self.view addSubview:calendarTableView];
    self.calendarTableView = calendarTableView;
    
    // 箭头线
    UIImageView *lineImgView = [[UIImageView alloc] init];
    lineImgView.image = [UIImage imageNamed:@"line"];
    [self.view addSubview:lineImgView];
    [lineImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(calendarTableView.mas_bottom).offset(5);
        make.height.mas_equalTo(8);
    }];
    
    // 月份显示按钮
    UIButton *monthBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [monthBtn setTitleColor:YAYIColor(106, 177, 242) forState:UIControlStateNormal];
    [monthBtn setTitleColor:YAYIColor(90, 160, 220) forState:UIControlStateHighlighted];
    [monthBtn setTitle:@"5月" forState:UIControlStateNormal];
    monthBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    [monthBtn addTarget:self action:@selector(onMonthBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:monthBtn];
    self.monthBtn = monthBtn;
    [monthBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view);
        make.top.mas_equalTo(64);
        make.right.mas_equalTo(calendarTableView.mas_left);
        make.bottom.mas_equalTo(calendarTableView);
    }];
    [self.tableView setContentOffset:CGPointZero animated:YES];
}


/**
 *  底部view
 */
- (void)setupBottomView
{
    UIView *bottomView = [[UIView alloc] init];
//    bottomView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(self.tableView.mas_bottom).offset(10);
        make.width.mas_equalTo(SCREEN_width);
        make.bottom.mas_equalTo(self.view);
    }];
    
    // 每半小时可接诊数
    UIView *hLineView1 = [[UIView alloc] init];
    hLineView1.backgroundColor = YAYIColor(183, 184, 185);
    [bottomView addSubview:hLineView1];
    [hLineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_width);
        make.height.mas_equalTo(0.5);
    }];
    
    UILabel *treatCountLbl = [[UILabel alloc] init];
    treatCountLbl.text = @"每半小时可接诊数";
    treatCountLbl.font = [UIFont systemFontOfSize:16];
    treatCountLbl.textColor = YAYIColor(112, 108, 108);
    [bottomView addSubview:treatCountLbl];
    [treatCountLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(bottomView).offset(-50);
        make.centerY.mas_equalTo(bottomView).multipliedBy(0.5);
    }];
    
    // 可接诊数按钮
    UIButton *treatCountBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [treatCountBtn setTitle:@"1" forState:UIControlStateNormal];
    treatCountBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [treatCountBtn setTitleColor:YAYIColor(102, 171, 235) forState:UIControlStateNormal];
    treatCountBtn.layer.cornerRadius = 5;
    treatCountBtn.layer.borderWidth = 1;
    treatCountBtn.layer.borderColor = YAYIColor(102, 171, 235).CGColor;
    [treatCountBtn addTarget:self action:@selector(onTreatCountBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:treatCountBtn];
    self.treatCountBtn = treatCountBtn;
    [treatCountBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(treatCountLbl.mas_right).offset(10);
        make.centerY.mas_equalTo(treatCountLbl);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(22);
    }];
    
    // 复制上周，清空本周
    UIView *hLineView2 = [[UIView alloc] init];
    hLineView2.backgroundColor = YAYIColor(183, 184, 185);
    [bottomView addSubview:hLineView2];
    [hLineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.centerY.mas_equalTo(bottomView);
        make.width.mas_equalTo(SCREEN_width);
        make.height.mas_equalTo(0.5);
    }];
    
    // 复制上周
    UIButton *copyLastWeekBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [copyLastWeekBtn setTitle:@"复制上周出诊时间" forState:UIControlStateNormal];
    copyLastWeekBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [copyLastWeekBtn setTitleColor:YAYIColor(112, 108, 108) forState:UIControlStateNormal];
    [copyLastWeekBtn setImage:[UIImage imageNamed:@"schedulingIcon1"] forState:UIControlStateNormal];
    [copyLastWeekBtn setImage:[UIImage imageNamed:@"schedulingIcon1"] forState:UIControlStateHighlighted];
    [copyLastWeekBtn addTarget:self action:@selector(onCopyLastWeekBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:copyLastWeekBtn];
    [copyLastWeekBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(hLineView2.mas_bottom);
        make.width.mas_equalTo(SCREEN_width * 0.5);
        make.bottom.mas_equalTo(0);
    }];
    
    // 清空本周
    UIButton *clearThisWeekBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [clearThisWeekBtn setTitle:@"清空本周出诊时间" forState:UIControlStateNormal];
    clearThisWeekBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [clearThisWeekBtn setTitleColor:YAYIColor(112, 108, 108) forState:UIControlStateNormal];
    [clearThisWeekBtn setImage:[UIImage imageNamed:@"schedulingIcon2"] forState:UIControlStateNormal];
    [clearThisWeekBtn setImage:[UIImage imageNamed:@"schedulingIcon2"] forState:UIControlStateHighlighted];
    [clearThisWeekBtn addTarget:self action:@selector(onClearThisWeekBtnClickClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:clearThisWeekBtn];
    [clearThisWeekBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(bottomView.mas_centerX);
        make.top.mas_equalTo(hLineView2.mas_bottom);
        make.width.mas_equalTo(SCREEN_width * 0.5);
        make.bottom.mas_equalTo(0);
    }];
    
    // 竖线
    UIView *vLineView2 = [[UIView alloc] init];
    vLineView2.backgroundColor = YAYIColor(183, 184, 185);
    [bottomView addSubview:vLineView2];
    [vLineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(bottomView);
        make.top.mas_equalTo(hLineView2.mas_bottom);
        make.width.mas_equalTo(0.5);
        make.bottom.mas_equalTo(0);
    }];
}


/**
 *  清空模型数据
 */
- (void)clearSchedulingModelData
{
    for (YAYISchedulingItemModel *schedulingItem in self.schedulingModelArray) {
        schedulingItem.schedulingModel = nil;
    }
}


#pragma mark - 获取数据
- (void)getSchedulingData:(NSString *)hospitalID
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"wpid"] = hospitalID;
    
    // 用来保证网络接口调用了想要的次数再刷新tableview
    __block NSInteger getDataTimes = self.monthParamArray.count;
    for (int i = 0; i < self.monthParamArray.count; i++) {
        
        param[@"queryMonth"] = self.monthParamArray[i];
        YAYILog(@"param%d %@", i, param);
        
        [YAYINetWorking getWithURL:listAllWorkTime_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
            
            YAYILog(@"返回:%@", dict);
            
            if ([dict[@"status"] isEqualToString:@"redirect"]) { // 未登录
                
                UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"" message:@"您还没有登录，是否现在去登录?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                alerView.tag = NotLoginAlertTag;
                [alerView show];
                return;
            }
            
            if ([dict[@"status"] isEqualToString:@"success"]) {
                NSArray *dat = dict[@"data"];
                if (dat.count != 0) {
                    for (NSDictionary *obj in dat) {
                        YAYISchededdModel *model = [[YAYISchededdModel alloc] init];
                        [model setValuesForKeysWithDictionary:obj];
                        
                        // workdate转换成时间戳：workdate : 2016-06-04,
                        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                        formatter.dateFormat = @"YYYY-MM-dd";
                        NSDate *workDate = [formatter dateFromString:model.workdate];
                        NSInteger workDateStamp = [workDate timeIntervalSince1970];
                        NSInteger difference = workDateStamp - self.startDayTimeStamp;
                        
                        NSInteger index = difference / (24 * 60 * 60);
                        if (index >= 0 && index <= self.dateModelArray.count - 1) {
                            
                            YAYISchedulingItemModel *schedulingItemmodel = self.schedulingModelArray[index];
                            schedulingItemmodel.schedulingModel = model;
                        }
                    }
                }
                
                getDataTimes--;
                if (getDataTimes == 0) {
                    [self.tableView reloadData];
                }
            }
        }];
    }
    
}


/**
 *  获取医院列表
 */
- (void)getHospitalList
{
    if (self.hospitalArray.count > 0) {
        return;
    }
    
    [YAYINetWorking getWithURL:myHospital_url param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回:%@", dict);
            
            if (dict != nil) {
                
                if ([dict[@"status"] isEqualToString:@"redirect"]) { // 未登录
                    
                    UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"" message:@"您还没有登录，是否现在去登录?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    alerView.tag = NotLoginAlertTag;
                    [alerView show];
                    return;
                }
                
                if ([dict[@"data"] isEqual:NULL]) {
                   
                    return ;
                }else{
                    
                    NSArray *data = dict[@"data"];
                    for (NSDictionary *obj in data) {
                        YAYIHosiptalModel *model = [[YAYIHosiptalModel alloc] init];
                        model.name = obj[@"name"];
                        model.wpid = obj[@"wpid"];
                        [self.hospitalArray addObject:model];
                        
                        YAYILog(@"model.id:%@ model.name:%@", obj[@"wpid"], model.name);
                        
                    }
                    
                    if (self.hospitalArray.count > 0) {
                        [self.dropMenu refreshData:self.hospitalArray];
                        [self.dropMenu selectRow:0];
                        
                        // 刷新列表
                        YAYIHosiptalModel *hostModel = self.hospitalArray[0];
                        self.hospitalID = hostModel.wpid;
                        [self getSchedulingData:hostModel.wpid];
                    }
                }
                
            }else{
                YAYILog(@"网络异常");
            }
        }
        
    }];
}


/**
 *  添加排班调用接口
 */
- (void)addSchedulingWithParam:(NSMutableDictionary *)param isClose:(BOOL)isClose bookingTimeids:(NSString *)bookingTimeids
{
    param[@"num"] = self.treatCountBtn.titleLabel.text;
    param[@"bookingTimeids"] = bookingTimeids;
    param[@"isClose"] = isClose ? @"Y": @"N";
    
    YAYILog(@"param:%@", param);
    
    
    [YAYINetWorking postJsonSerilizeWithURL:addWorkTime_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error, NSDictionary *responseError) {
        if (nil == error) {
            YAYILog(@"返回：%@", dict);
            
            if (![dict isKindOfClass:[NSNull class]] && [dict[@"status"] isEqualToString:@"success"]) {
                
                // 记得清空临时保存的修改数据的字典
                [self.changedItemDict removeAllObjects];
                
                YAYILog(@"self.changedItemDict:%@", self.changedItemDict);
                
                // 设置右边保存按钮变为分享
                UIButton *rightBtn = self.navigationItem.rightBarButtonItem.customView;
                [rightBtn setTitle:@"分享" forState:UIControlStateNormal];
                
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
                
                if (!isClose) {
                    // 刷新数据
                    [self clearSchedulingModelData];
                    [self getSchedulingData:self.hospitalID];
                }
            }else{
                [SVProgressHUD showErrorWithStatus:@"保存失败"];
            }
        }
    }];
}


- (void)copyLastWeek
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"wpid"] = self.hospitalID;
    param[@"num"] = self.treatCountBtn.titleLabel.text;

    // 取出日期
    YAYICalendarModel *model = self.dateModelArray[self.weekIndex * 7];
    param[@"startdate"] = [NSString stringWithFormat:@"%ld-%02ld-%02ld", model.year, model.month, model.day];
    YAYILog(@"param:%@", param);

    [YAYINetWorking postJsonSerilizeWithURL:copyWorktime_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error, NSDictionary *responseError) {
        
        YAYILog(@"返回:%@", dict);
        
        if (nil == error) {
            
            if (![dict isKindOfClass:[NSNull class]] && [dict[@"status"] isEqualToString:@"success"]) {
                
                NSString *message = dict[@"message"];
                NSRange range = [message rangeOfString:@"复制上周排班成功"];
                if (range.location == NSNotFound) {
                    
                    [SVProgressHUD showErrorWithStatus:message];
                }else{
                
                    [SVProgressHUD showSuccessWithStatus:message];
                }
                
                // 刷新tableview
                [self clearSchedulingModelData];
                [self getSchedulingData:self.hospitalID];
            }else{
                NSString *message = dict[@"message"];
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"\n\n%@\n\n", message]];
            }
        }else{
        
            YAYILog(@"error:%@", responseError);
        }
    }];
}


/**
 * 清空本周排班前检查是否有预约
 */
- (void)beforeClear
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"wpid"] = self.hospitalID;
    // 取出日期
    YAYICalendarModel *model = self.dateModelArray[self.weekIndex * 7];
    param[@"startdate"] = [NSString stringWithFormat:@"%ld-%02ld-%02ld", model.year, model.month, model.day];
    YAYILog(@"param:%@", param);
    
    [YAYINetWorking getWithURL:beforeReset_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        YAYILog(@"返回:%@", dict);
        
        if (![dict isKindOfClass:[NSNull class]] && [dict[@"status"] isEqualToString:@"success"]) {
            
            NSString *dataStr = dict[@"data"];
            if (dataStr.length > 0) {
                self.param = param;
                self.bookingTimeids = dict[@"data"];
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"该排班已有患者预约，确定清空排班吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                alertView.tag = ClearThisWeekHaveBookingAlertTag;
                [alertView show];
                
            }else{
                [self clearThisMonthWithParam:param bookingTimeids:dict[@"data"]];
            }
            
        }else{
            
        }
    }];
}


/**
 *  删除本周排班
 */
- (void)clearThisMonthWithParam:(NSMutableDictionary *)param bookingTimeids:(NSString *)bookingTimeids
{
    param[@"worktimeids"] = bookingTimeids;
    param[@"isClose"] = @"Y";
    YAYILog(@"param:%@", param);
    
    [YAYINetWorking postJsonSerilizeWithURL:resetWorktime_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error, NSDictionary *responseError) {
        if (nil == error) {
            YAYILog(@"返回：%@", dict);
            
            if (![dict isKindOfClass:[NSNull class]] && [dict[@"status"] isEqualToString:@"success"]) {
                [SVProgressHUD showSuccessWithStatus:@"清除成功"];
                // 刷新数据
                [self clearSchedulingModelData];
                [self getSchedulingData:self.hospitalID];
            }else{
                [SVProgressHUD showErrorWithStatus:@"清除失败"];
            }
        }else{
            YAYILog(@"error:%@", responseError);
        }
    }];
}


#pragma mark - 点击事件
- (void)onMonthBtnClick:(UIButton *)sender
{
    YAYILog(@"月份按钮点击！");
    YAYIDateController *dateVc = [[YAYIDateController alloc] init];
    dateVc.hospitalID = self.hospitalID;
    [self.navigationController pushViewController:dateVc animated:YES];
}


- (void)onTitleBtnClick:(UIButton *)sender
{
    YAYILog(@"选择医院！");
}


- (void)onSaveBtnClick:(UIButton *)sender
{
    
    NSString *rightBtnTitle = [sender titleForState:UIControlStateNormal];
    
    // 右边按钮是分享还是保存
    if ([rightBtnTitle isEqualToString:@"分享"]) {
        
        YAYILog(@"点击了分享");

        YAYIShareView *shareView = [[YAYIShareView alloc] initWithDelegate:self];
        shareView.imageUrlStr = self.avatarUrlStr;
        // https://wx.yayi365.cn/reservation/reservation_resdet.html?doctorid=1
        
        
        // 这里doctor那么不知道为什么出现nil，待查
        if (!self.doctorName) {
            NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
            self.doctorName = [userDef valueForKey:YAYIDoctorNameKey];
            self.doctorID = [NSString stringWithFormat:@"%zd", [userDef integerForKey:YAYIUserIDKey]];
            self.avatarUrlStr = [NSString stringWithFormat:@"%@%@", API, [userDef valueForKey:YAYIDoctorAvatarKey]];
        }
        // 拼接链接地址
        NSString *qrCodeUrl = [NSString stringWithFormat:@"%@?doctorid=%@", WXShareAPI, self.doctorID];
        
        shareView.urlStr = qrCodeUrl;
        shareView.shareTitle = [NSString stringWithFormat:@"[预约我的出诊时间] %@医生—雅同", self.doctorName];
        shareView.shareContent = @"足不出户就能预约专家。再也不用排队两小时，对话两分钟了。";
        [shareView show];
        return;
    }else if ([rightBtnTitle isEqualToString:@"保存"]){
        
        YAYILog(@"保存！");
        // 停诊的是否有预约
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"wpid"] = self.hospitalID;
        
        // 拼接参数
        NSMutableArray *worktimes = [NSMutableArray array];
        NSArray *keyArray = [self.changedItemDict allKeys];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        for (int i = 0; i < keyArray.count; i++) {
            int key = [keyArray[i] intValue];
            NSMutableDictionary *worktimeParam = [NSMutableDictionary dictionary];
            // 取出对应日期格式 2016-05-15
            formatter.dateFormat = @"YYYY-MM-dd";
            YAYICalendarModel *calendarModel = self.dateModelArray[key];
            worktimeParam[@"workdate"] = [formatter stringFromDate:calendarModel.date];
            
            NSArray *keyArray = [self.changedItemDict[@(key)] allKeys];
            NSMutableArray *worktimeArray = [NSMutableArray array];
            for (id subKey in keyArray) {
                
                NSString *typeStr = [subKey intValue] == 0 ? @"morning" : @"afternoon";
                int isOpen = [self.changedItemDict[@(key)][subKey] intValue];
                NSMutableDictionary *worktime = [NSMutableDictionary dictionary];
                worktime[@"type"] = typeStr;
                
                if (isOpen == 1) {
                    worktime[@"status"] = @"0";
                }else{
                    worktime[@"status"] = @"1";
                }
                
                [worktimeArray addObject:worktime];
            }
            
            worktimeParam[@"worktime"] = worktimeArray;
            [worktimes addObject:worktimeParam];
        }
        
        param[@"worktimes"] = worktimes;
        param[@"num"] = self.treatCountBtn.titleLabel.text;
        
        YAYILog(@"onSaveBtnClick param:%@", param);
        
        [YAYINetWorking postJsonSerilizeWithURL:queryHasBooking_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error, NSDictionary *responseError) {
            if (nil == error) {
                YAYILog(@"返回：%@", dict);
                
                if (![dict isKindOfClass:[NSNull class]] && [dict[@"status"] isEqualToString:@"success"]) {
                    NSString *dataStr = dict[@"data"];
                    if (dataStr.length > 0) {
                        
                        self.param = param;
                        self.bookingTimeids = dict[@"data"];
                        
                        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"该排班已有患者预约，确定要关闭排班并发布停诊通知吗?" delegate:self cancelButtonTitle:@"不关闭" otherButtonTitles:@"关闭通知", nil];
                        alertView.tag = HaveBookingAlertTag;
                        [alertView show];
                        
                    }else{
                        // 添加排班
                        [self addSchedulingWithParam:param isClose:YES bookingTimeids:dict[@"data"]];
                    }
                }
            }
        }];
    }
}


/**
 *  选择器相关方法
 */
- (void)onTreatCountBtnClick:(UIButton *)sender
{
    YAYILog(@"选择半小时可接诊数");
    
    // 添加覆盖层
    UIView *maskView = [[UIView alloc] init];
    maskView.backgroundColor = [UIColor blackColor];
    maskView.alpha = 0.2;
    maskView.frame = CGRectMake(0, 0, SCREEN_width, SCREEN_height);
    [self.view.window addSubview:maskView];
    self.maskView = maskView;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(maskViewClick:)];
    [maskView addGestureRecognizer:singleTap];
    
    // 创建dataselect view
    UIView *selectView = [[UIView alloc] init];
    selectView.backgroundColor = [UIColor whiteColor];
    [self.view.window addSubview:selectView];
    self.dateSelectView = selectView;
    self.dateSelectView.alpha = 0.3;
    selectView.frame = CGRectMake(0, SCREEN_height * 0.6, SCREEN_width, SCREEN_height * 0.4);
    [selectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@200);
        make.width.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(200);
        make.left.equalTo(self.view);
    }];
    
    //
    UIPickerView *pickerView = [[UIPickerView alloc] init];
    pickerView.backgroundColor = [UIColor whiteColor];
    self.dateSelectView.alpha = 1;
    pickerView.delegate = self;
    pickerView.dataSource = self;
    [selectView addSubview:pickerView];
    self.pickerView = pickerView;
    
    [pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(selectView);
        
    }];
    
    
    // 添加取消按钮
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [cancelBtn setTitleColor:YAYIColor(103, 176, 254) forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [selectView addSubview:cancelBtn];
    [cancelBtn addTarget:self action:@selector(onCancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@50);
        make.height.equalTo(@30);
        make.left.equalTo(pickerView).offset(15);
        make.top.equalTo(pickerView).offset(10);
    }];
    
    // 添加完成按钮
    UIButton *finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [finishBtn setTitle:@"完成" forState:UIControlStateNormal];
    finishBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [finishBtn setTitleColor:YAYIColor(103, 176, 254) forState:UIControlStateNormal];
    [finishBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [selectView addSubview:finishBtn];
    [finishBtn addTarget:self action:@selector(onFinishBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@50);
        make.height.equalTo(@30);
        make.right.equalTo(pickerView).offset(-15);
        make.top.equalTo(pickerView).offset(10);
    }];
    
    
    
    [selectView layoutIfNeeded];
    
    [selectView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        [selectView layoutIfNeeded];
    }];
}


/**
 *  隐藏选择器
 */
- (void)hideDataSelecter
{
    [self.dateSelectView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(200);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.maskView.alpha = 0;
        [self.dateSelectView layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self.maskView removeFromSuperview];
        [self.dateSelectView removeFromSuperview];
        self.maskView = nil;
        self.dateSelectView = nil;
    }];
}


- (void)maskViewClick:(UITapGestureRecognizer *)sender
{
    
    [self hideDataSelecter];
}


- (void)onCancelBtnClick:(UIButton *)sender
{
    [self hideDataSelecter];
}


- (void)onFinishBtnClick:(UIButton *)sender
{
    NSInteger selectRow = [self.pickerView selectedRowInComponent:0];
    [self.treatCountBtn setTitle:[NSString stringWithFormat:@"%ld", selectRow + 1] forState:UIControlStateNormal];
    
    [self hideDataSelecter];
}


- (void)onCopyLastWeekBtnClick:(UIButton *)sender
{
    YAYILog(@"复制上周");
    
    if (self.weekIndex == 0) {
        [SVProgressHUD showImage:nil status:@"\n\n已过期排班\n\n"];
        return;
    }
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"确定要复制上周出诊时间吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"复制", nil];
    alertView.tag = CopyLastWeekAlertTag;
    [alertView show];
}


- (void)onClearThisWeekBtnClickClick:(UIButton *)sender
{
    YAYILog(@"清空本周");
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"确定要清空本周出诊时间吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"清空", nil];
    alertView.tag = ClearThisWeekAlertTag;
    [alertView show];
}


#pragma mark - 工具方法
/**
 *  这个月有几天
 */
- (NSInteger)totaldaysInThisMonth:(NSDate *)date{
    NSRange totaldaysInMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return totaldaysInMonth.length;
}


/**
 *  第一天是周几
 */
- (NSInteger)firstWeekdayInThisMonth:(NSDate *)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:1];//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
    NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    [comp setDay:1];
    NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
    NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonthDate];
    return firstWeekday - 1;
}


/**
 *  今天是周几
 */
- (NSInteger)weekdayInToday:(NSDate *)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:1];//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
    NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
//    [comp setDay:1];
    NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
    NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonthDate];
    return firstWeekday - 1;
}


#pragma mark - 代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.schedulingModelArray.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    CGFloat schedulingW = (SCREEN_width - 44) / 7.0;
    return self.cellHeight;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == CalenDarTag) { // 日历tableview
        
        YAYICalendarCell *cell = [YAYICalendarCell cellWith:tableView];
        
        cell.contentView.transform = CGAffineTransformMakeRotation(M_PI_2);
        
        YAYICalendarModel *model = self.dateModelArray[indexPath.row];
        cell.model = model;
        
        return cell;
        
    }else{ // 排班tableview
        YAYISchedulingItemModel *model = self.schedulingModelArray[indexPath.row];
    
        YAYISchedulingCell *cell = [YAYISchedulingCell cellWith:tableView];
        cell.indexPath = indexPath;
        cell.delegate = self;
        cell.contentView.transform = CGAffineTransformMakeRotation(M_PI_2);
        if (0 == indexPath.row) {
            cell.lineType = LineTypeNormal;//LineTypeFirst;
        }else{
            cell.lineType = LineTypeNormal;
        }
        
        cell.model = model;
        
        return cell;
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.tag == CalenDarTag) {
    }else{
        self.calendarTableView.contentOffset = scrollView.contentOffset;
    }
    
    // 这里移动tableview最左边的线
    CGPoint offset = scrollView.contentOffset;
    if (offset.y < 0) {

        self.leftLineView.transform = CGAffineTransformMakeTranslation(-offset.y, 0);
    }
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.tag == CalenDarTag) {
    }else{
        [self scrollViewDidEndScrollingAnimation:scrollView];
    }
    
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    if (scrollView.tag == CalenDarTag) {
    }else{
        NSInteger index = (NSInteger)(scrollView.contentOffset.y / scrollView.bounds.size.height);
        self.weekIndex = index;
        
        YAYICalendarModel *model = self.dateModelArray[index* 7 + 3];
        NSString *curMonthStr = [NSString stringWithFormat:@"%ld月", model.month];
        [self.monthBtn setTitle:curMonthStr forState:UIControlStateNormal];
    }
}


#pragma mark pickerView代理
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}


- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return 9;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [NSString stringWithFormat:@"%ld", row + 1];
}


#pragma mark UIAlertView代理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        if (alertView.tag == HaveBookingAlertTag) { // 排班有患者预约
            
            [self addSchedulingWithParam:self.param isClose:YES bookingTimeids:self.bookingTimeids];
        }else if (alertView.tag == CopyLastWeekAlertTag){ // 复制上周
            
            [self copyLastWeek];
        }else if (alertView.tag == ClearThisWeekAlertTag){ // 清空本周
            
            [self beforeClear];
        }else if (alertView.tag == ClearThisWeekHaveBookingAlertTag){ // 清空本周，有患者预约
            
            [self clearThisMonthWithParam:self.param bookingTimeids:self.bookingTimeids];
        }else if (alertView.tag == NotLoginAlertTag){ // 未登录
            
            YAYILoginViewController *loginView = [YAYILoginViewController new];
            __block typeof(self) weakself = self;
            loginView.loginSuccessOperation = ^(){
                YAYILog(@"登陆成功");
                [weakself getHospitalList];
            };
            
            loginView.cancelOperation = ^(){
                YAYILog(@"取消登陆");
                [weakself.navigationController popViewControllerAnimated:YES];
            };
            
            YAYINavigationController *nav = [[YAYINavigationController alloc] initWithRootViewController:loginView];
            [self presentViewController:nav animated:YES completion:nil];
        }
    }else if (buttonIndex == 0){ // 取消
        
        if (alertView.tag == HaveBookingAlertTag) { // 排班有患者预约
            [self addSchedulingWithParam:self.param isClose:NO bookingTimeids:self.bookingTimeids];
        }else if (alertView.tag == NotLoginAlertTag){ // 未登录
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}


#pragma mark YAYISchedulingCellDelegate代理
- (BOOL)schedulingCellItemViewDidCickAtIndex:(NSInteger)index withIndexPath:(NSIndexPath *)indexPath state:(BOOL)isOpen
{
    YAYILog(@"%ld行%ld列被点击,%d",indexPath.row, index, isOpen);
    
    // 判断在其他医院有没有排班， 不能再多个医院重复排班
    YAYISchedulingItemModel *itemModel = self.schedulingModelArray[indexPath.row];
    
    if (itemModel.schedulingModel && itemModel.schedulingModel.scheduledTimeModelArray.count > 0) {
        for (YAYIScheduledTimeModel *scheduleTimeModel in itemModel.schedulingModel.scheduledTimeModelArray) {
            
            NSInteger type = -1;
            if ([scheduleTimeModel.type isEqualToString:@"morning"]) {
                
                type = 0;
            }else if ([scheduleTimeModel.type isEqualToString:@"afternoon"]) {
                
                type = 1;
            }
            
            if (type == index && [scheduleTimeModel.iscurrent isEqualToString:@"N"]) {
                YAYILog(@"已有排班");
                return NO;
            }
        }
    }
    
    
    // 改变模型数据
    YAYISchedulingItemModel *model = self.schedulingModelArray[indexPath.row];
    model.flagArray[index] = @(isOpen ? 1 : 0);
    YAYILog(@"model.flagArray:%@", model.flagArray);
    
    // 保存更改状态, 我这里用一个大字典保存更改过的数据{1 : {0 : 1, 1 : 1} }
    NSMutableDictionary *dayItemDict = self.changedItemDict[@(indexPath.row)];
    
    if (dayItemDict) {
        
        if(dayItemDict[@(index)]){
            
            [dayItemDict removeObjectForKey:@(index)];
            if (dayItemDict.allKeys.count == 0) {
                [self.changedItemDict removeObjectForKey:@(indexPath.row)];
            }
        }else{
            dayItemDict[@(index)] = isOpen ? @(1) : @(0);
        }
    }else{
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@(index)] = isOpen ? @(1) : @(0);
        self.changedItemDict[@(indexPath.row)] = dict;
    }
    
    // 判断有无修改，如果有修改改变右边按钮为“保存”, 否则为分享
    if (self.changedItemDict.allKeys.count > 0) {
        
        // 设置右边保存按钮变为保存
        UIButton *rightBtn = self.navigationItem.rightBarButtonItem.customView;
        [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    }else{
        
        // 设置右边保存按钮变为分享
        UIButton *rightBtn = self.navigationItem.rightBarButtonItem.customView;
        [rightBtn setTitle:@"分享" forState:UIControlStateNormal];
    }
    
    YAYILog(@"self.changedItemDict:%@", self.changedItemDict);
    return YES;
}


#pragma mark YAYIDropMenuView代理
- (void)selectColum:(NSInteger)colum
{
    YAYILog(@"选择了低%ld列", colum);

//    [self getHospitalList];
}


- (void)selectRow:(NSInteger)row Model:(YAYIHosiptalModel *)model
{
    YAYILog(@"选择了第%ld行, %@ id:%@", row, model.name, model.wpid);
    
    // 先清除数据
    self.hospitalID = model.wpid;
    [self clearSchedulingModelData];
    [self getSchedulingData:model.wpid];
}


@end
